package guiservice.server.controls;

import lombok.extern.log4j.Log4j;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTextArea;

@Log4j
public class TextArea extends Control implements guiservice.common.controls.TextArea {

    private JTextArea textBox;

    private List<String> strings = new ArrayList<>();

    private int index = 0;

    public void appendText(String text) {
        strings.add(text);
        index += 1;
        updateVisibleText();
    }

    @Override
    public void moveScroll(int diffAmountOfString) {
        int temp = index + diffAmountOfString;
        if (temp < 0) {
            index = 0;
        } else if (temp >= strings.size()) {
            index = strings.size() - 1;
        } else {
            index = temp;
        }
        updateVisibleText();
        log.debug(String.format("index=%d, size=%d", index, strings.size()));
    }

    private void updateVisibleText() {
        int min = index - 3;
        while (min < 0) {
            min++;
        }
        log.debug(String.format("min index=%d, size=%d", min, strings.size()));
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 3; i++) {
            int current = min + i;
            if (current < strings.size()) {
                sb.append(strings.get(current));
                sb.append(String.format("%n"));
            }
        }
        textBox.setText(sb.toString());
    }

    public TextArea(long id, long owner) {
        super(id, owner, guiservice.common.controls.TextArea.class.getCanonicalName());
        textBox = new JTextArea();
        textBox.setFont(new Font("Calibry", 0, 12));
    }

    protected Component getComponent() {
        return textBox;
    }

    @Override
    public String getText() {
        return textBox.getText();
    }

    @Override
    public void setText(String text) {
        textBox.setText(text);
    }

}
